package com.itheima.threadDemo;

/*
同步方法和代码块
 */
public class Demo8 {
    public static void main(String[] args) {
        RunnableTicket rt = new RunnableTicket();
        Thread t1 = new Thread(rt);
        Thread t2 = new Thread(rt);
        t1.setName("小周");
        t2.setName("小杨");
        t1.start();
        t2.start();


    }
}

class RunnableTicket implements Runnable {
    private static int ticket = 100;

    @Override
    public void run() {
        while (true) {
            if ("小周".equals(Thread.currentThread().getName())) {
                //同步方法
                boolean res = synchronizedmethod();
                if (res) {
                    break;
                }
            }

            //同步代码块
            if ("小杨".equals(Thread.currentThread().getName())) {
                //加了一把锁.如果是静态方法可以使用类名点上class,否则可以用this
                synchronized (RunnableTicket.class) {
                    if (ticket <= 0) {
                        break;
                    } else {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        ticket--;
                        System.out.println(Thread.currentThread().getName() + "还剩" + ticket + "张票");


                    }

                }
            }
        }
    }

    //这是同步方法
    private static synchronized boolean synchronizedmethod() {
        if (ticket <= 0) {
            return true;
        } else {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ticket--;
            System.out.println(Thread.currentThread().getName() + "还剩" + ticket + "张票");
            return false;
        }

    }
}